package com.cn.medicalcare.service;

import com.cn.medicalcare.customtool.JsonTool;
import com.cn.medicalcare.customtool.SqlSessionFactoryTool;
import com.cn.medicalcare.mapper.AdvertisementMapper;
import com.cn.medicalcare.pojo.AdContent;
import com.cn.medicalcare.pojo.Advertisement;

import java.util.*;

public class AdvertisementService {

    //静态内部类单例模式
    private static class SingletonClassInstance{
        private static final AdvertisementService instance=new AdvertisementService();
    }

    private AdvertisementService(){}

    public static AdvertisementService getInstance(){
        return AdvertisementService.SingletonClassInstance.instance;
    }


    public String getAdvertisementJson(){
        List<Advertisement> list= SqlSessionFactoryTool.DoMapper(AdvertisementMapper.class,mapper->mapper.selectAll());
//        封装Advertisement数据
        Map<String,Map<String,List<AdContent>>> ads=new LinkedHashMap<>();
        Map<String,List<AdContent>> categorymap;
        List<AdContent> elelist;
        if(list!=null){
            String ad_="ad";//广告的属性前缀名
            for (Advertisement ad:list){
                String adnum=ad_+ad.getAdnum();
                if(ads.containsKey(adnum)){//当广告组ads中有当前所属广告时
                    categorymap=ads.get(adnum);//取出
                    if(categorymap.containsKey(ad.getCategory())){//当前广告中有所属类别的数组时
                        elelist=categorymap.get(ad.getCategory());//取出
                    }else {
                        elelist=new ArrayList<>();//没有，就新建一个
                    }

                }else {//没有，就新建广告
                    categorymap=new HashMap<>();
                    elelist=new ArrayList<>();
                }
                //然后添加对象后放回
                elelist.add(new AdContent(ad.getId(),ad.getContent()));
                categorymap.put(ad.getCategory(),elelist);
                ads.put(adnum,categorymap);
            }
        }

        return JsonTool.toJson(ads);
    }
}
